# 测试登录49服务器

import os,sys

current_dir = os.path.dirname(os.path.abspath(__file__))  
current_parent=os.path.dirname(current_dir)
sys.path.append(os.path.join(current_parent))

from selenium.webdriver.common.by import By
from pylibs import SeleniumUtil
from pylibs import ImageUtil
from pylibs import OcrUtil
from time import sleep    




# 指定ChromeDriver的路径（如果你已经将其添加到系统环境变量中，则不需要这行代码）  
driver_path = 'd:/apps/chromedriver/chromedriver.exe'  

driver=SeleniumUtil.initWebDriver(driver_path)
driver.get("http://49.233.50.97:8096/")  

icnt=0
while True:
    
    # 检测页面是否是等了页面
    elemValidatePage=SeleniumUtil.findElement( driver=driver,waitTime=3,
                                            value="div.primeton-login-form h2.mb-3",innerText="登录")
    
    if elemValidatePage is None:
        print('当前不是登录页面')

        cookies = driver.get_cookies()

        icnt+=1
        print(f'==================={icnt}')
        for cookie in cookies:  
            print(f"Cookie Name: {cookie['name']}, Cookie Value: {cookie['value']}") 

        driver.refresh()
    else:
        print('当前是登录页面')

        # 获取账号密码等页面组件
        elemUsername=SeleniumUtil.findElement( driver=driver, value="input#form_item_userName")
        elemUserpwd=SeleniumUtil.findElement( driver=driver, value="input#form_item_password")
        elemImgValidateCode=SeleniumUtil.findElement( 
            driver=driver, value="form.ant-form div.ant-col-8 div.ant-form-item-control-input-content img"
            ,waitTime=0)
        elemInputValidateCode=SeleniumUtil.findElement( 
            driver=driver, value="input#form_item_inputCode"
            ,waitTime=0)
        
        # 验证登录账号和密码的控件存在
        if elemUsername is not None and elemUserpwd is not None:
            elemUsername.clear()
            elemUsername.send_keys('abc123')

            elemUserpwd.clear()
            elemUserpwd.send_keys('abc')

            # 如何页面有验证码，则读取验证码中的文字
            if elemImgValidateCode is not None:

                # 获取base64的值
                strBase64=elemImgValidateCode.get_attribute(name='src')
                # base64转为 bytes
                imgBytes=ImageUtil.base64ToBytes(strbase64=strBase64)

                # bytes 中获取验证码的文字 
                str1=OcrUtil.textFromBytes(imgBytes)
                print(f'=============={str1}')

                if elemInputValidateCode is  not None:
                    elemInputValidateCode.clear()
                    elemInputValidateCode.send_keys(f'{str1}')

            elemBtnLogin=SeleniumUtil.findElement( driver=driver,innerText='登 录',
                                                  value="form.ant-form div.ant-form-item-control-input-content button.ant-btn-lg")
            if elemBtnLogin is not None:
                elemBtnLogin.click()


        
    sleep(12)
    
